package serialport;

import android.content.Context;
import android.os.Environment;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.example.administrator.baseproject.BaseClass;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import singleton.SingletonClass;
import utils.DigitalTrans;
import utils.TimeUtil;
import utils.ToastUtil;

/**
 * Created by admin on 2018/1/16.
 */
public class DealFingerprintSerialPortData extends BaseClass {
    private OutputStream mOutputStream;
    private Context mContext;
    private MyHandler allHandler;
    private boolean isError = true;//判断是否失败(失败和第三次注册,都会返回03)
    private String userId;
    private String TAG = "DealFingerplPortData";
    private int count;
    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    public DealFingerprintSerialPortData(OutputStream mOutputStream, Context mContext) {
        this.mOutputStream = mOutputStream;
        this.mContext = mContext;
        allHandler = SingletonClass.getSingleton(MyHandler.class);
    }
    private byte[] data;

    public void receiveData(byte[] receiveData) {
        readAccordCommandType(receiveData);
    }

    private void readAccordCommandType(byte[] receiveData) {
        data = receiveData;
        int commandType = receiveData[1] & 0xFF;
        int resultType = receiveData[4] & 0xFF;
        switch (commandType) {
            case 0x01:

                if (resultType == Constants.ACK_SUCCESS) {
                    isError = true;
                    allHandler.sendEmptyMessage(HandlerConstant.FINGERPRINT_REGISTER_FIRST_RETURN);

                } else {
                    fingerprintResult(resultType);
                }
                break;
            case 0x02:

                if (resultType == Constants.ACK_SUCCESS) {
                    isError = false;
                    allHandler.sendEmptyMessage(HandlerConstant.FINGERPRINT_REGISTER_SECOND_RETURN);
                } else {
                    fingerprintResult(resultType);
                }
                break;
            case 0x03:
//                Toast.makeText(mContext,"3",Toast.LENGTH_SHORT);
                if (isError) {
                    allHandler.sendEmptyMessage(HandlerConstant.FINGERPRINT_REGISTER_ERROR);
                } else {
                    if (resultType == Constants.ACK_SUCCESS) {
                        allHandler.sendEmptyMessage(HandlerConstant.FINGERPRINT_REGISTER_THIRD_RETURN);
                        //注册成功时,获取该用户特征值
//                    StringBuilder sbCommand = new StringBuilder();
//                    sbCommand.append("31");
//                    sbCommand.append(DigitalTrans.toHexStringByte(receiveData[2]));
//                    sbCommand.append(DigitalTrans.toHexStringByte(receiveData[3]));
//                    sbCommand.append("0000");
//                    writeToFingerprint(sbCommand.toString());

                        Message message = allHandler.obtainMessage();
                        message.obj = DigitalTrans.toHexStringByte(receiveData[2]) + DigitalTrans.toHexStringByte(receiveData[3]);
                        Log.e("GGG", "id : " + DigitalTrans.toHexStringByte(receiveData[2]) + DigitalTrans.toHexStringByte(receiveData[3]));
                        message.what = HandlerConstant.GET_FINGERPRINT_FEATURE;
                        sendFrameMessage(message);
                    } else {
                        fingerprintResult(resultType);
                    }

                }
                break;
            case 0x04:
                if (resultType == Constants.ACK_SUCCESS) {
                    allHandler.sendEmptyMessage(HandlerConstant.DELETE_FINGERPRINT_USER_SUCCESS);
                } else {
                    allHandler.sendEmptyMessage(HandlerConstant.DELETE_FINGERPRINT_USER_FAIL);
                }
                break;
            case 0x0C:
                //若用户id不为0,则验证成功
                if ((receiveData[2] & 0xFF) != 0 || (receiveData[3] & 0xFF) != 0) {
                    Message message = allHandler.obtainMessage();
                    message.obj = DigitalTrans.toHexStringByte(receiveData[2]) + DigitalTrans.toHexStringByte(receiveData[3]);
                    message.what = HandlerConstant.FINGERPRINT_VERIFICATION_SUCCESS;
                    allHandler.sendMessage(message);
//                    allHandler.sendEmptyMessage(HandlerConstant.FINGERPRINT_VERIFICATION_SUCCESS);
                } else {
                    //08是指纹输入超时
//                    if (resultType == Constants.ACK_TIMEOUT) {
//                        allHandler.sendEmptyMessage(HandlerConstant.FINGERPRINT_VERIFICATION_TIMEOUT);
//                    } else {
////                        allHandler.sendEmptyMessage(HandlerConstant.FINGERPRINT_VERIFICATION_WITHOUT_USER);
//                        fingerprintResult(resultType);
//                    }
                    if (resultType == Constants.ACK_SUCCESS) {
                        allHandler.sendEmptyMessage(HandlerConstant.FINGERPRINT_VERIFICATION_FAIL);
                    } else {
                        fingerprintResult(resultType);
                    }
                }
                break;
            case 0x31:
                if (resultType == Constants.ACK_SUCCESS) {
                    Message message = allHandler.obtainMessage();
                    String completeData = DigitalTrans.toHexString(receiveData);
//                    userId = completeData.substring(18, 22);
//                    message.obj = completeData.substring(24, completeData.length() - 4);
                    message.obj = completeData.substring(18, completeData.length() - 4);
                    message.what = HandlerConstant.FINGERPRINT_FEATURE_SUCCESS;
                    allHandler.sendMessage(message);
                } else {
                    fingerprintResult(resultType);
                }
                break;
            case 0x41:
//                if (resultType == Constants.ACK_SUCCESS) {
                    allHandler.sendEmptyMessage(HandlerConstant.TRANSFER_FINGERPRINT_FEATURE_SUCCESS);
//                } else {
//                    fingerprintResult(resultType);
//                }
                break;

        }
    }


    public void fingerprintResult(int resultType) {
        switch (resultType) {
//            case Constants.ACK_SUCCESS:
//                switch (commandType){
//
//                }
//                allHandler.sendEmptyMessage(HandlerConstant.ACK_SUCCESS);
//                break;
            case Constants.ACK_FAIL:
                allHandler.sendEmptyMessage(HandlerConstant.ACK_FAIL);
                break;
            case Constants.ACK_FULL:
                Log.e(TAG, "fingerprintResult: " + data.toString() );
                allHandler.sendEmptyMessage(HandlerConstant.ACK_FULL);
                break;
            case Constants.ACK_NOUSER:
                allHandler.sendEmptyMessage(HandlerConstant.ACK_NOUSER);
                break;
            case Constants.ACK_USER_EXIST:
                allHandler.sendEmptyMessage(HandlerConstant.ACK_USER_EXIST);
                break;
            case Constants.ACK_TIMEOUT:
                if (!allHandler.hasMessages(HandlerConstant.ACK_TIMEOUT)) {
                    allHandler.sendEmptyMessage(HandlerConstant.ACK_TIMEOUT);
                }
                break;
            case Constants.ACK_BREAK:
                allHandler.sendEmptyMessage(HandlerConstant.ACK_BREAK);
                break;
            case Constants.ACK_IMAGEFIAL:
                allHandler.sendEmptyMessage(HandlerConstant.ACK_IMAGEFIAL);
                break;
            case 0x10:
                Log.e("GGG", "fingerprintResult: " );
//                allHandler.sendEmptyMessage(HandlerConstant.ACK_FULL);
                break;
        }
    }

    @Override
    public void onHandleFrameMessage(Message msg) {
        switch (msg.what) {
            case HandlerConstant.FINGERPRINT_REGISTER_FIRST:
                writeToFingerprint("0100000100");
                Log.e("GGG", "first: ");
                break;
            case HandlerConstant.FINGERPRINT_REGISTER_SECOND:
//                Toast.makeText(mContext,"me second",Toast.LENGTH_SHORT);
                writeToFingerprint("0200000000");
                Log.e("GGG", "second: ");
                break;
            case HandlerConstant.FINGERPRINT_REGISTER_THIRD:
//                Toast.makeText(mContext,"me third",Toast.LENGTH_SHORT);
                writeToFingerprint("0300000000");
                Log.e("GGG", "third: ");
                break;
            case HandlerConstant.FINGERPRINT_VERIFICATION:
                Log.e("GGG", "发送验证指令: ");
                writeToFingerprint("0C00000000");
                break;
            case HandlerConstant.GET_FINGERPRINT_FEATURE:
                writeToFingerprint("31" + msg.obj + "0000");
                break;
            case HandlerConstant.DELETE_FINGERPRINT_USER:
                Log.e(TAG, "onHandleFrameMessage: " + Integer.parseInt((String) msg.obj,16) );
                saveToFile(" delete : " + Integer.parseInt((String) msg.obj,16));
                writeToFingerprint("04" + msg.obj + "0000");
                break;
            case HandlerConstant.TRANSFER_FINGERPRINT_FEATURE:
                saveToFile(" transfer : " + msg.arg1);
                writeToFingerprint("410F170000");
                writeToFingerprint(DigitalTrans.hexNumberFormat(msg.arg1, 4) + "01" + msg.obj);
                break;
            case HandlerConstant.CANCLE_FINGERPRINT_COMMAND:
                writeToFingerprint("FE00000000");
                break;
            case HandlerConstant.TEST:
                writeToFingerprint("0500000000");//删除所有用户
//                writeToFingerprint("0900000000");//获取用户总数
//                writeToFingerprint("FE00000000");
                break;
        }
    }

    //往指纹模组写数据
    private void writeToFingerprint(String command) {
        Log.e(TAG, "writeToFingerprint: "+DigitalTrans.getFingerprintCommand(command) );
        try {
            mOutputStream.write(DigitalTrans.hexStringToByteArray(DigitalTrans.getFingerprintCommand(command)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void saveToFile(String receiveData) {
        StringBuffer sb = new StringBuffer();
        try {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {

                String time = formatter.format(new Date());
                sb.append(time);
                sb.append("  --begin--:  ");
                sb.append(receiveData);
                sb.append("  --end--;  ");
                sb.append("\r\n");
                String fileName = TimeUtil.getYear()+"-"+(TimeUtil.getMonth()+1)+"-"+TimeUtil.getDay()+".log";
                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/fingerprint/";

                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                FileOutputStream fos = new FileOutputStream(path + fileName, true);
                fos.write(sb.toString().getBytes());
                fos.flush();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
